package client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.UUID;

public class Client {

	private String ipScheduler;
	private int portScheduler;
	private String pathToWorkLoad;
	private File workLoad;
	private Hashtable<String, Task> tasks;
	private Socket sock=null;
	
	Client(){
		ipScheduler = "";
		portScheduler = 0;
		pathToWorkLoad ="";
		workLoad = null;
		tasks = new Hashtable<String, Task>();
		
	}
	
	public void setSocket(){
		try {
			sock = new Socket(ipScheduler, portScheduler);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void fillTasks(){
		BufferedReader b=null;
		try {
			b = new BufferedReader(new FileReader(workLoad));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String line="";
		try {
			while((line = b.readLine()) != null){
				UUID uuid = UUID.randomUUID();
				Task t = new Task(uuid);
				t.setTimeToSleep(Integer.parseInt(line.split(" ")[1]));
				tasks.put(uuid.toString(), t);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendTasksToScheduler(){
		Socket sock = null;
		DataOutputStream dos=null;
		String sendString= "1";
	
		setSocket();
		
		try {
			dos = new DataOutputStream(sock.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 for (Enumeration<String> e = tasks.keys(); e.hasMoreElements();){
			sendString+=" ";
			sendString+= e.nextElement()+"/"+tasks.get(e.nextElement()).getTimeToSleep();
		}
		
		try {
			dos.writeChars(sendString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getIpScheduler() {
		return ipScheduler;
	}

	public boolean setIpScheduler(String ipScheduler) {
		if(ipScheduler.matches("\\d{3}\\.\\d{3}\\.\\d{3}:\\d{1,6}")){
			String[] ipPort = ipScheduler.split(":");
			this.ipScheduler = ipPort[0];
			this.portScheduler = Integer.parseInt(ipPort[1]);
			return true;
		}
		return false;

	}

	public String getPathToWorkLoad() {
		return pathToWorkLoad;
	}

	public boolean setPathToWorkLoad(String pathToWorkLoad) {
		workLoad = new File(pathToWorkLoad);
		if(workLoad.isFile()){
			this.pathToWorkLoad = pathToWorkLoad;
			return true;
		}
		workLoad = null;
		return false;
	}

	public Socket getSocket(){
		return sock;
	}

	public int nbTasks() {
		
		return tasks.size();
	}

	public Hashtable<String, Task> getTasks(){
		return tasks;
	}

}
